package com.ikingtech.platform.service.authentication;

import com.ikingtech.framework.sdk.authenticate.embedded.authenticate.DelegateAuthenticate;
import com.ikingtech.framework.sdk.authenticate.embedded.core.Credential;
import com.ikingtech.framework.sdk.context.security.Identity;
import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.enums.log.SignTypeEnum;
import com.ikingtech.framework.sdk.log.embedded.annotation.AuthLog;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.framework.sdk.web.annotation.ApiController;
import com.ikingtech.framework.sdk.web.annotation.Encrypted;
import com.ikingtech.framework.sdk.web.annotation.PostRequest;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.RequestBody;

import jakarta.servlet.http.HttpServletRequest;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
@ApiController(name = "认证中心", description = "认证中心")
public class AuthenticationHandler {

    private final DelegateAuthenticate delegate;

    /**
     * 用户登录
     *
     * @param credential 用户身份凭证
     * @return 登录结果
     */
    @AuthLog(type = SignTypeEnum.SIGN_IN)
    @PostRequest(order = 1, value = "/sign", summary = "用户登录", description = "用户登录")
    public R<Identity> signIn(@Parameter(name = "credential", description = "用户身份凭证")
                              @Encrypted(fields = "password")
                              @RequestBody Credential credential) {
        // 调用代理对象进行用户身份认证
        Identity identity = this.delegate.authenticate(credential);
        // 判断认证是否成功，成功则返回用户身份信息，否则返回认证失败原因
        return Boolean.TRUE.equals(identity.getAuthenticated()) ? R.ok(identity) : R.failed(identity.getCause());
    }

    /**
     * 退出登录
     *
     * @param request 请求对象
     * @return 返回登录信息
     */
    @AuthLog(type = SignTypeEnum.SIGN_OUT)
    @PostRequest(order = 2, value = "/sign-out", summary = "退出登录", description = "退出登录")
    public R<Object> signOut(HttpServletRequest request) {
        // 获取Authorization头
        String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (Tools.Str.isBlank(authorization)) {
            return R.failed("invalidAuthorizationHeader");
        }
        // 取消认证
        this.delegate.cancelAuthenticate(authorization);
        return R.ok();
    }
}
